import React, { useState, useEffect } from 'react';
import { Card, Typography, Space, Tag, Button, Row, Col, Descriptions, Image, Divider, Spin, Empty, message } from 'antd';
import { ClockCircleOutlined, ShoppingOutlined, CheckCircleOutlined, CloseCircleOutlined, LeftOutlined } from '@ant-design/icons';
import { getOrderDetail, payOrder, cancelOrder } from '../api/divide/order/sdk.gen';
import type { OrderVo } from '../api/divide/order/types.gen';
import { useNavigate, useParams } from 'react-router-dom';

const { Title, Text } = Typography;

const OrderDetail: React.FC = () => {
  const [order, setOrder] = useState<OrderVo | null>(null);
  const [loading, setLoading] = useState(false);
  const [paying, setPaying] = useState(false);
  const [cancelling, setCancelling] = useState(false);
  
  const { orderId } = useParams<{ orderId: string }>();
  const navigate = useNavigate();

  // 订单状态映射 - 现在直接使用字符串状态
  const statusMap = {
    '待支付': { text: '待支付', color: 'orange', icon: <ClockCircleOutlined /> },
    '已支付': { text: '已支付', color: 'blue', icon: <ShoppingOutlined /> },
    '已完成': { text: '已完成', color: 'green', icon: <CheckCircleOutlined /> },
    '已取消': { text: '已取消', color: 'red', icon: <CloseCircleOutlined /> },
    '已退款': { text: '已退款', color: 'purple', icon: <CloseCircleOutlined /> },
  };
  
  // 获取状态信息的安全函数 - 适配字符串状态
  const getStatusInfo = (status: string | undefined) => {
    const defaultStatus = { text: '未知', color: 'default', icon: <ClockCircleOutlined /> };
    return status ? statusMap[status as keyof typeof statusMap] || defaultStatus : defaultStatus;
  };

  // 获取订单详情
  const fetchOrderDetail = async () => {
    if (!orderId) return;
    
    setLoading(true);
    try {
      const response = await getOrderDetail({
        path: { id: parseInt(orderId) }
      });
      if (response.data?.code === 200 && response.data.data) {
        setOrder(response.data.data);
      } else {
        message.error('获取订单详情失败');
      }
    } catch (error) {
      console.error('获取订单详情失败:', error);
      message.error('获取订单详情失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrderDetail();
  }, [orderId]);

  // 处理支付
  const handlePay = async () => {
    if (!order?.orderId) return;
    
    setPaying(true);
    try {
      const response = await payOrder({
        body: { orderId: order.orderId, paymentMethod: 1 }
      });
      if (response.data?.code === 200) {
        message.success('支付成功');
        fetchOrderDetail(); // 重新获取订单详情
      } else {
        message.error(response.data?.message || '支付失败');
      }
    } catch (error) {
      console.error('支付失败:', error);
      message.error('支付失败');
    } finally {
      setPaying(false);
    }
  };

  // 处理取消订单
  const handleCancel = async () => {
    if (!order?.orderId) return;
    
    setCancelling(true);
    try {
      const response = await cancelOrder({
        body: { orderId: order.orderId }
      });
      if (response.data?.code === 200) {
        message.success('取消订单成功');
        fetchOrderDetail(); // 重新获取订单详情
      } else {
        message.error(response.data?.message || '取消订单失败');
      }
    } catch (error) {
      console.error('取消订单失败:', error);
      message.error('取消订单失败');
    } finally {
      setCancelling(false);
    }
  };

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!order) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Empty description="订单不存在" />
      </div>
    );
  }

  const statusInfo = getStatusInfo(order.status);

  return (
    <div style={{ padding: '24px' }}>
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <Button 
            type="text" 
            icon={<LeftOutlined />}
            onClick={() => navigate('/orders')}
          >
            返回订单列表
          </Button>
          <Title level={2} style={{ margin: 0 }}>订单详情</Title>
        </div>

        <Row gutter={24}>
          <Col span={16}>
            <Card title="订单信息">
              <Descriptions column={2} bordered>
                <Descriptions.Item label="订单号">
                  <Text strong>{order.orderNo}</Text>
                </Descriptions.Item>
                <Descriptions.Item label="订单状态">
                  <Tag color={statusInfo.color} icon={statusInfo.icon}>
                    {statusInfo.text}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="课程名称">
                  <Text strong>{order.courseTitle}</Text>
                </Descriptions.Item>
                <Descriptions.Item label="课程级别">
                  <Text>高级</Text>
                </Descriptions.Item>
                <Descriptions.Item label="课程时长">
                  <Text>12小时</Text>
                </Descriptions.Item>
                <Descriptions.Item label="订单金额">
                  <Text strong style={{ color: '#ff4d4f', fontSize: '18px' }}>
                    ¥{order.amount}
                  </Text>
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {new Date(order.createTime).toLocaleString('zh-CN')}
                </Descriptions.Item>
                {order.expireTime && (
                  <Descriptions.Item label="过期时间">
                    {new Date(order.expireTime).toLocaleString('zh-CN')}
                  </Descriptions.Item>
                )}
              </Descriptions>
            </Card>

            <Card title="课程封面" style={{ marginTop: 16 }}>
              <Image
                width={300}
                src={order.courseCover || 'https://via.placeholder.com/300x200'}
                alt={order.courseTitle}
                style={{ borderRadius: 8 }}
              />
            </Card>
          </Col>

          <Col span={8}>
            <Card title="订单操作">
              <Space direction="vertical" style={{ width: '100%' }}>
                {order.status === '待支付' && (
                  <>
                    <Button 
                      type="primary" 
                      size="large" 
                      block
                      loading={paying}
                      onClick={handlePay}
                    >
                      立即支付
                    </Button>
                    <Button 
                      danger 
                      block
                      loading={cancelling}
                      onClick={handleCancel}
                    >
                      取消订单
                    </Button>
                  </>
                )}
                {order.status === '已支付' && (
                  <Button type="primary" size="large" block>
                    开始学习
                  </Button>
                )}
                {order.status === '已完成' && (
                  <Button type="primary" size="large" block>
                    继续学习
                  </Button>
                )}
                {order.status === '已取消' && (
                  <Text type="secondary" style={{ textAlign: 'center' }}>
                    订单已取消
                  </Text>
                )}
                {order.status === '已退款' && (
                  <Text type="secondary" style={{ textAlign: 'center' }}>
                    订单已退款
                  </Text>
                )}
              </Space>
            </Card>

            <Card title="订单状态说明" style={{ marginTop: 16 }}>
              <Space direction="vertical" size="small">
                <Text type="secondary">
                  <ClockCircleOutlined /> 待支付：订单已创建，等待付款
                </Text>
                <Text type="secondary">
                  <ShoppingOutlined /> 已支付：付款成功，可以开始学习
                </Text>
                <Text type="secondary">
                  <CheckCircleOutlined /> 已完成：课程学习已完成
                </Text>
                <Text type="secondary">
                  <CloseCircleOutlined /> 已取消：订单已取消，无需支付
                </Text>
              </Space>
            </Card>
          </Col>
        </Row>
      </Space>
    </div>
  );
};

export default OrderDetail;